import json
from flask import request
from funcy import project
from sqlalchemy.exc import IntegrityError
from flask_restful import abort

from redash import models
from redash.handlers.base import BaseResource, require_fields, get_object_or_404


class CrudResource(BaseResource):
    def delete(self, query_id, tablename, id, keyname='id'):
        sql = "delete from " + tablename + " where " + keyname + "='" + str(id) + "';select * from " + tablename + " where 1>1"

        query = models.Query.get_by_id(query_id)
        result, error = query.data_source.query_runner.run_query(sql, self.current_user)
        if error:
            return str(error).split("\n")[0];
        else:
            return True;

    def post(self, query_id, tablename, id=0, keyname='id'):
        req = request.get_json(force=True)
        if len(req) == 0:
            return None

        if id == 0 or id == '0':
            sql = "insert into " + tablename + " (" +  ",".join(req.keys()) + ") values ("
            for k in req.keys(): 
                sql = sql + "'" + str(req[k]) + "',"
            sql = sql[:-1] + ");select * from " + tablename + " where 1>1"
        else:
            sql = "update " + tablename + " set "
            for k in req.keys(): 
                sql = sql + k + "='" + str(req[k]) + "',"
            sql = sql[:-1] + " where " + keyname + "='" + str(id) + "';select * from " + tablename + " where 1>1"

        query = models.Query.get_by_id(query_id)
        result, error = query.data_source.query_runner.run_query(sql, self.current_user)
        if error:
            return str(error).split("\n")[0];
        else:
            return True;
